﻿using System;
using System.Linq;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using ComApp.Model;
using ComApp;

namespace AndroidApp
{
    [Activity(Theme = "@android:style/Theme.NoTitleBar")]
    public class DownloadView : BaseActivity
    {
        private Button downloadFileButton;
        private Button cancelDownloadButton;
        private Button scanButton;
        private Button scanButton2;

        private Button openFile;

        private ProgressBar downloadProgressBar;
        private TextView downloadFileInfoTextView;
        private string TempCode { get; set; }
        private string FileName { get; set; }
        private Guid FileItemID { get; set; }

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            this.SetChildContentView(Resource.Layout.DownloadView);
            AppUnity.Instance.LogService.Log("Open DownloadView成功");
            this.TempCode = Intent.GetStringExtra("TempCode");

            downloadFileButton = FindViewById<Button>(Resource.Id.downloadFileButton);
            downloadFileButton.Click += (s, e) =>
                {
                    var url = string.Format("http://{0}/Default/File/Index/{1}", AppUnity.Instance.ServerDeploy.WebServerHostName, this.FileItemID);
                    this.DownloadFile(url, this.FileName);
                };

            cancelDownloadButton = FindViewById<Button>(Resource.Id.cancelDownloadButton);
            cancelDownloadButton.Click += (s, e) =>
                {
                    this.CancelDownload();
                };

            downloadProgressBar = FindViewById<ProgressBar>(Resource.Id.downloadProgress);
            downloadFileInfoTextView = this.FindViewById<TextView>(Resource.Id.downloadFileInfoTextView);

            scanButton = FindViewById<Button>(Resource.Id.scanButton);
            scanButton.Click += (s, e) =>
            {
                this.OpenScanView();
            };

            scanButton2 = FindViewById<Button>(Resource.Id.scanButton2);
            scanButton2.Click += (s, e) =>
            {
                this.OpenScanView();
            };

            openFile = FindViewById<Button>(Resource.Id.openFile);
            openFile.Click += (s, e) =>
            {
                var filePath = System.IO.Path.Combine(HttpService.Instance.DownloadPath, this.FileName);
                if (System.IO.File.Exists(filePath))
                    FileManager.Instance.OpenFile(this, filePath);
            };

            //openFolder = FindViewById<Button>(Resource.Id.openFolder);
            //openFolder.Click += (s, e) =>
            //{
            //    var filePath = System.IO.Path.Combine(HttpService.Instance.DownloadPath, this.FileName);
            //    if (System.IO.File.Exists(filePath))
            //        FileManager.Instance.OpenFolder(this, HttpService.Instance.DownloadPath);
            //};

            if (string.IsNullOrEmpty(this.TempCode))
            {
                this.SetScanView();
            }
            else
            {
                this.RefreshDownloadFile(this.TempCode);
            }
        }

        private void OpenScanView()
        {
            var scanner = new MobileBarcodeScanner(this);
            scanner.UseCustomOverlay = true;
            var zxingOverlay = LayoutInflater.FromContext(this).Inflate(Resource.Layout.ZxingOverlay, null);
            scanner.CustomOverlay = zxingOverlay;
            var result = scanner.Scan();
            result.ContinueWith((r) => this.RunOnUiThread(() => { HandleScanResult(r.Result); }));

            //string text = "http://siai.org";
            //var r = new ZXing.Result(text,null,null, ZXing.BarcodeFormat.QR_CODE);
            //this.HandleScanResult(r);
        }


        private void HandleScanResult(ZXing.Result result)
        {
            if (result == null || string.IsNullOrEmpty(result.Text))
            {
                Toast.MakeText(this, "扫描已取消！", ToastLength.Short).Show();
                return;
            }

            var text = result.Text.ToLower();
            var http = string.Format("http://{0}/", AppUnity.Instance.ServerDeploy.WebServerHostName);
            if (text.StartsWith(http))
            {
                var tempFileCode = text.Substring(http.Length);
                if (tempFileCode.Length == 6)
                {
                    this.RefreshDownloadFile(tempFileCode);
                    return;
                }
            }

            if (text.StartsWith("http://"))
            {
                FileManager.Instance.OpenUrl(this, text);
            }
            else
            {
                Toast.MakeText(this, result.Text, ToastLength.Long).Show();
            }
        }

        private void SetScanView()
        {
            this.openFile.Visibility = ViewStates.Gone;
            this.scanButton2.Visibility = ViewStates.Visible;
            this.downloadFileButton.Visibility = ViewStates.Gone;
            this.cancelDownloadButton.Visibility = ViewStates.Gone;
            downloadProgressBar.Visibility = ViewStates.Gone;
            downloadFileInfoTextView.Visibility = ViewStates.Gone;
        }


        private void SetDownloadingView(string filePath)
        {
            this.openFile.Visibility = ViewStates.Gone;
            this.scanButton2.Visibility = ViewStates.Gone;
            this.downloadFileButton.Visibility = ViewStates.Gone;
            this.cancelDownloadButton.Visibility = ViewStates.Visible;
            this.downloadProgressBar.Visibility = ViewStates.Visible;
            downloadFileInfoTextView.Visibility = ViewStates.Visible;
        }

        private void RefreshDownloadFile(string tempFileCode)
        {
            this.TempCode = tempFileCode;
            using (var client = new WcfTempFileServiceRef.WcfTempFileService())
            {
                client.Url = AppUnity.Instance.ServerDeploy.WcfTempFileUrl;
                Action<AndroidApp.WcfTempFileServiceRef.TempFile> action = (tempFile) =>
                {
                    Action<AndroidApp.WcfTempFileServiceRef.FileItem> actionFileItem = (fileItem) =>
                    {
                        this.FileName = fileItem.FileName;
                        this.FileItemID = Guid.Parse(tempFile.FileItemID);
                        downloadFileInfoTextView.Text = string.Format("{0}({1})", this.FileName, this.GetFileSize(fileItem.FileSize));
                        this.SetDownloadView();
                    };

                    var fileItemID = Guid.Parse(tempFile.FileItemID);
                    this.GetFileItemByID(client, fileItemID, actionFileItem);
                };

                this.GetTempFileByCode(client, tempFileCode, action);
            }
        }

        private void GetTempFileByCode(WcfTempFileServiceRef.WcfTempFileService client, string tempFileCode, Action<AndroidApp.WcfTempFileServiceRef.TempFile> action)
        {
            client.GetTempFileByCodeCompleted += (s, e) =>
            {
                AppUnity.Instance.RunOnUiThread(() =>
                {
                    var tempFile = e.Result;
                    action(tempFile);
                });
            };
            AppUnity.Instance.LogService.Log(string.Format("读取TempFileByCode{0}", tempFileCode));
            client.GetTempFileByCodeAsync(ThisApp.Instance.AppDeploy.CurrentUser.ID.ToString(), tempFileCode);
        }

        private void GetFileItemByID(WcfTempFileServiceRef.WcfTempFileService client, Guid fileItemID, Action<AndroidApp.WcfTempFileServiceRef.FileItem> action)
        {
            client.GetFileItemByIDCompleted += (s, e) =>
            {
                AppUnity.Instance.RunOnUiThread(() =>
                {
                    var fileItem = e.Result;
                    action(fileItem);
                });
            };
            AppUnity.Instance.LogService.Log(string.Format("读取FileItemByID{0}", fileItemID));
            client.GetFileItemByIDAsync(ThisApp.Instance.AppDeploy.CurrentUser.ID.ToString(), fileItemID.ToString());
        }


        private void SetDownloadView()
        {
            this.openFile.Visibility = ViewStates.Gone;
            this.scanButton2.Visibility = ViewStates.Gone;
            this.downloadFileButton.Visibility = ViewStates.Visible;
            this.cancelDownloadButton.Visibility = ViewStates.Gone;
            downloadProgressBar.Visibility = ViewStates.Gone;
            downloadFileInfoTextView.Visibility = ViewStates.Visible;
        }

        private void SetDownloadedView()
        {
            this.openFile.Visibility = ViewStates.Visible;
            this.scanButton2.Visibility = ViewStates.Gone;
            this.downloadFileButton.Visibility = ViewStates.Gone;
            this.cancelDownloadButton.Visibility = ViewStates.Gone;
            downloadProgressBar.Visibility = ViewStates.Gone;
            downloadFileInfoTextView.Visibility = ViewStates.Visible;
        }

        private void CancelDownload()
        {
            HttpService.Instance.CancelDownload();
            this.SetDownloadView();
            Toast.MakeText(this, "下载取消.", ToastLength.Short).Show();
            AppUnity.Instance.LogService.Log("下载取消");
        }

        protected override bool CloseBeforeExit()
        {
            return true;
        }

        bool isFirst = true;
        protected override void OnResume()
        {
            base.OnResume();
            if (isFirst)
            {
                isFirst = false;
                AppUnity.Instance.LogService.Log("DownloadView.OnResume First...");
            }
            else
            {
                AppUnity.Instance.LogService.Log("DownloadView.OnResume More...");
            }
        }

        private void DownloadFile(string downloadFileUrl, string fileName)
        {
            var filePath = System.IO.Path.Combine(HttpService.Instance.DownloadPath, fileName);
            Action<System.IO.MemoryStream> downloadedAction = (ms) =>
                {
                    if (System.IO.File.Exists(filePath))
                        System.IO.File.Delete(filePath);

                    using (var f = new System.IO.FileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        ms.WriteTo(f);
                    }

                    downloadFileInfoTextView.Text = string.Format("下载完成,文件:{0}", this.FileName);
                    //Todo:加入到下载列表中
                    this.SetDownloadedView();
                    AppUnity.Instance.LogService.Log("下载完成.");
                };

            var fileText = System.IO.Path.GetFileNameWithoutExtension(filePath);
            var fileExt = System.IO.Path.GetExtension(filePath);
            Action<long, long> progressAction = (d, l) =>
            {
                downloadFileInfoTextView.Text = string.Format("正在下载{0}{1}: {2}/{3}", fileText.TrimOrDot(10), fileExt, this.GetFileSize(d), this.GetFileSize(l));
            };

            try
            {
                this.SetDownloadingView(filePath);
                HttpService.Instance.DownloadFile(downloadFileUrl, progressAction, downloadedAction);
            }
            catch
            {
                this.SetDownloadView();
                Toast.MakeText(this, "下载失败.", ToastLength.Short).Show();
                AppUnity.Instance.LogService.Log("下载失败");
                throw;
            }
        }

        private string GetFileSize(long fileLength)
        {
            var unit = "B";
            var fileSize = (decimal)fileLength;
            unit = "K";
            fileSize = ((decimal)fileSize / (decimal)1024);
            if (fileSize >= 1024)
            {
                unit = "M";
                fileSize = ((decimal)fileSize / (decimal)1024);
            }
            if (fileSize >= 1024)
            {
                unit = "G";
                fileSize = ((decimal)fileSize / (decimal)1024);
            }

            return string.Format("{0}{1}", fileSize.ToString("#,##0.#"), unit);
        }

    }
}

